<?php

namespace app\common\third;

use app\common\BaseLogic;

class Wechat extends BaseLogic
{
    protected $baseUrl = 'https://qyapi.weixin.qq.com';
    protected $agentid;
    protected $corpid;
    protected $corpsecret;
    protected $access_token;

    function __construct()
    {
        // 继承父类构造函数
        parent::__construct();
        $systemConfigLogic = new \app\common\config\logic\ConfigSystem();
        $config = $systemConfigLogic->getConfigItem('work_wechat');
        $this->agentid = $config['agent_id'];
        $this->corpid = $config['corp_id'];
        $this->corpsecret = $config['secret'];

        $this->get_access_token();
    }

    private function http_request($url, $method, $data = null)
    {
        $url = $this->baseUrl . $url;
        $options = [
            'http' => [
                'header' => "Content-type: application/json\r\n",
                'method' => $method,
                'content' => $data,
            ],
        ];
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return json_decode($result, true);
    }

    private function get_access_token()
    {
        $cacheName = 'work_wechat_access_token';
        $this->access_token = $this->redis->get($cacheName);

        if (!$this->access_token) {
            $url = "/cgi-bin/gettoken?corpid={$this->corpid}&corpsecret={$this->corpsecret}";
            $response = $this->http_request($url, 'GET');

            $this->access_token = $response['access_token'];
            // 将access_token存入缓存
            $this->redis->set($cacheName, $this->access_token, 7200);
        }
    }

    public function get_user_info($code)
    {
        $url = "/cgi-bin/user/getuserinfo?access_token={$this->access_token}&code={$code}";
        return $this->http_request($url, 'GET');
    }

    public function get_user_id($mobile)
    {
        $url = "/cgi-bin/user/getuserid?access_token={$this->access_token}&debug=1";
        $data = array(
            'mobile' => $mobile,
        );

        return $this->http_request($url, 'POST', json_encode($data));
    }

    public function send_text_message($touser, $content)
    {
        $message = array(
            'content' => $content,
        );

        return $this->send_message($touser, 'text', $message);
    }

    public function send_message($touser, $msgtype, $message)
    {
        $url = "/cgi-bin/message/send?access_token={$this->access_token}";
        $data = array(
            'touser' => $touser,
            'msgtype' => $msgtype,
            'agentid' => $this->agentid,
            $msgtype => $message,
            "safe" => 0,
            "enable_id_trans" => 0,
            "enable_duplicate_check" => 0,
            "duplicate_check_interval" => 1800
        );
        
        return $this->http_request($url, 'POST', json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
}
